from flask import Blueprint, render_template, request, jsonify
from utils import query_aliyun
from exts import mongo
from math import *


bp = Blueprint("front", __name__)


@bp.route('/')
def index():
    devices = list(mongo.db.hardware.find({}))
    return render_template('index.html', devices=devices)


@bp.route('/view/')
def view():
    args = request.args
    device_name = args.get('device_name')
    identifier = args.get('identifier')
    return render_template('view.html', device_name=device_name, identifier=identifier)


@bp.route('/addDevice/', methods=['POST'])
def add_device():
    form = request.form
    device_name = form.get('device_name')
    product_key = form.get('product_key')
    identifier = form.get('identifier')
    if device_name == '' or product_key == '' or identifier == '':
        message = '值不能为空，添加失败！'
        return jsonify({'code': 200, 'message': message, 'data': []})

    mongo.db.hardware.insert({'device_name': device_name, 'product_key': product_key, 'identifier': identifier})
    message = '添加成功！！！'
    return jsonify({'code': 200, 'message': message, 'data': []})


@bp.route('/data/')
def get_data():
    args = request.args
    device_name = args.get('device_name')
    identifier = args.get('identifier')
    operation = args.get('operation')

    device = list(mongo.db.hardware.find({'device_name': device_name, 'identifier': identifier}))
    # 如果没有查询到，返回查询失败
    if not device:
        message = '查询失败!!!'
        return jsonify({'code': 300, 'message': message, 'count': 0, 'data': []})

    product_key = device[0]['product_key']
    print(device[0])
    print(f'{device_name}即将执行 {operation} 操作...')

    # 后期应该通过device_name来获取get_data中的三个参数，然后获取数据，然后再对data数据执行operation操作
    data = query_aliyun.get_data(device_name, product_key, identifier)
    message = "运算成功!!!"
    try:
        for i, a_data in enumerate(data):
            x = a_data['value']
            if isinstance(x, str):
                x = float(x)
            data[i]['value'] = eval(operation)
    except:
        message = "运算失败!!!"

    return jsonify({"code": 200, "message": message, "count": len(data), "data": data})


@bp.route('/edit', methods=['POST'])
def get_edit():
    # if request.method == 'GET':
    #     return render_template('edit.html')
    # else:
    print(request.get_data(as_text=True))
    # form = request.form
    # print(form)
    # operation = form.get('operation')
    # print(operation)

    # 存储到mongodb

    return jsonify({'code': 200, 'message': '保存成功!', 'data': ''})


@bp.route('/test/', methods=['GET'])
def test():
    return render_template('edit.html')

